﻿using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections;
using System.IO;

public class BuildAssetBundles {

	[MenuItem("MyMenu/Build AssetBundle From Selection")]
	static void BuildAssetBundle() {
		//BuildPipeline.BuildAssetBundles(
		BuildPipeline.BuildAssetBundles(Application.dataPath, BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.ForceRebuildAssetBundle, BuildTarget.iOS); 
	}

	[MenuItem("MyMenu/Modify PlayerSetting")]
	static void ModifyPlayerSetting() {
		PlayerSettings.renderingPath = RenderingPath.Forward;
		//Debug.Log(EditorUserBuildSettings.activeBuildTargetChanged);
	}

	[MenuItem("MyMenu/BuildXcodeProject")]
	static void BuildXcode() {
		BuildPipeline.BuildPlayer (new string[] { "Assets/Game/Scenes/Benzhen.unity", "Assets/Game/Scenes/Battle.unity" }, "/Work/ngame-remote/ngamexcode1", BuildTarget.iOS, BuildOptions.AcceptExternalModificationsToPlayer);
	}

	[MenuItem ("MyMenu/AtlasMaker")]
	static private void MakeAtlas()
	{
		Debug.Log ("MakeAtlas");

		string spriteDir = Application.dataPath +"/Game/Resources/Sprite";

		if(!Directory.Exists(spriteDir)){
			Directory.CreateDirectory(spriteDir);
			Debug.Log ("Create Directory!");
		}

		Debug.Log ("Create Directory finished!");

		DirectoryInfo rootDirInfo = new DirectoryInfo (Application.dataPath +"/Game/UI");

		foreach (FileInfo pngFile in rootDirInfo.GetFiles("*.png",SearchOption.AllDirectories)) {
			Debug.Log ("Create file");

			string allPath = pngFile.FullName;
			string assetPath = allPath.Substring(allPath.IndexOf("Assets"));
			Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
			GameObject go = new GameObject(sprite.name);
			go.AddComponent<SpriteRenderer>().sprite = sprite;
			allPath = spriteDir+"/"+sprite.name+".prefab";
			string prefabPath = allPath.Substring(allPath.IndexOf("Assets"));
			PrefabUtility.CreatePrefab(prefabPath,go);
			//GameObject.DestroyImmediate(go);
		}

		Debug.Log (Application.dataPath + "/Game/UI");

		foreach (DirectoryInfo dirInfo in rootDirInfo.GetDirectories()) {
			Debug.Log (dirInfo.FullName);

			foreach (FileInfo pngFile in dirInfo.GetFiles("*.png",SearchOption.AllDirectories)) {
				Debug.Log ("Create file");

				string allPath = pngFile.FullName;
				string assetPath = allPath.Substring(allPath.IndexOf("Assets"));
				Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
				GameObject go = new GameObject(sprite.name);
				go.AddComponent<SpriteRenderer>().sprite = sprite;
				allPath = spriteDir+"/"+sprite.name+".prefab";
				string prefabPath = allPath.Substring(allPath.IndexOf("Assets"));
				PrefabUtility.CreatePrefab(prefabPath,go);
				//GameObject.DestroyImmediate(go);
			}
		}	
	}

}
